import tkinter as tk
from tkinter import filedialog, messagebox
from PyPDF2 import PdfReader, PdfWriter

def select_pdf():
    """选择需要拆分的PDF文件"""
    global pdf_path
    pdf_path = filedialog.askopenfilename(title="选择PDF文件", filetypes=[("PDF files", "*.pdf")])
    if pdf_path:
        entry_pdf.delete(0, tk.END)
        entry_pdf.insert(0, pdf_path)

def split_pdf():
    """根据提供的页码范围拆分PDF"""
    try:
        start_page = int(entry_start.get()) - 1  # 用户输入通常从1开始，而索引从0开始
        end_page = int(entry_end.get())
        reader = PdfReader(pdf_path)
        writer = PdfWriter()

        if start_page < 0 or end_page > len(reader.pages) or start_page >= end_page:
            messagebox.showerror("错误", "无效的页码范围")
            return

        for i in range(start_page, end_page):
            writer.add_page(reader.pages[i])

        output_filename = filedialog.asksaveasfilename(defaultextension=".pdf",
                                                        filetypes=[("PDF files", "*.pdf")])
        with open(output_filename, "wb") as out:
            writer.write(out)
        
        messagebox.showinfo("成功", "PDF拆分完成！")
    except Exception as e:
        messagebox.showerror("错误", str(e))

# GUI 界面初始化
root = tk.Tk()
root.title("PDF拆分工具")

pdf_path = ""

label_pdf = tk.Label(root, text="PDF文件:")
label_pdf.grid(row=0, column=0, padx=5, pady=5)

entry_pdf = tk.Entry(root, width=50)
entry_pdf.grid(row=0, column=1, padx=5, pady=5)

btn_select_pdf = tk.Button(root, text="选择PDF", command=select_pdf)
btn_select_pdf.grid(row=0, column=2, padx=5, pady=5)

label_start = tk.Label(root, text="起始页码:")
label_start.grid(row=1, column=0, padx=5, pady=5)

entry_start = tk.Entry(root)
entry_start.grid(row=1, column=1, padx=5, pady=5)

label_end = tk.Label(root, text="结束页码:")
label_end.grid(row=2, column=0, padx=5, pady=5)

entry_end = tk.Entry(root)
entry_end.grid(row=2, column=1, padx=5, pady=5)

btn_split = tk.Button(root, text="拆分PDF", command=split_pdf)
btn_split.grid(row=3, column=1, padx=5, pady=5)

root.mainloop()